import { Button, Table } from "antd";
import axios from "axios";
import React, { useEffect, useState } from "react";
import { useHistory } from "react-router-dom";
import { CheckOutlined, CloseOutlined } from "@ant-design/icons";
import { readToken } from "../../../util";

/** @import {News, NewsCategoryRoleDTO, ReactState} from "../../../types"; */

export default function Audit() {
    const history = useHistory();
    /** @type {ReactState<News[]>} */
    const [news, setNews] = useState([]);

    // 超级管理员可以审核所有人的新闻
    // 区域管理员只可以审核自己区域的新闻（包括自己的）
    const fetchData = () => {
        const {role, region} = readToken();
        axios.get("/news?_embed=category&auditState=1")
           .then((res) => {
                let data = res.data;
                if (role.roleType === 2)
                    data = data.filter((item) => item.region === region);
                setNews(data);
            });
    };
    useEffect(fetchData, []);

    const columns = [
        {
            title: "新闻标题",
            render: (news) => <a href={"#/news-manage/preview/" + news.id}>{news.title}</a>
        },
        {
            title: "作者",
            dataIndex: "author"
        },
        {
            title: "新闻分类",
            dataIndex: "category",
            render: (c) => c.title
        },
        {
            title: "操作",
            dataIndex: "auditState",
            /** @type {(as: number, news: News)} */
            render: (as, news) => (
                <div>
                    <Button type="primary" shape="circle" icon={<CheckOutlined />} onClick={() => handleAccept(news)} />
                    <Button danger shape="circle" icon={<CloseOutlined />} onClick={() => handleReject(news)} />
                </div>
            )
        }
    ];

    const handleAccept = (news) => {
        axios.patch("/news/" + news.id, {
            auditState: 2,
            publishState: 1,
            publishTime: new Date().getTime()
        })
        .then(fetchData);
    };

    const handleReject = (news) => {
        axios.patch("/news/" + news.id, {
            auditState: 3,
            publishState: 0
        })
        .then(fetchData);
    };
 
    return (
        <div>
            <Table dataSource={news} columns={columns} rowKey={(item) => item.id }/>
        </div>
    );
}
